package com.eptok.weixin.action;


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eptok.weixin.util.StrUtil;

import hikefa.core.remote.client.RemoteCall;
import yspay.express.bean.Result;
import yspay.express.util.AesUtil;
import yspay.express.util.CommonUtil;
import yspos.cpfs.express.entity.PospPayOrderInfo;
import yspos.cpfs.remoteserver.iface.IExpressService;

/**
* 
*	对外开放接口的接口
*	作者：邓磊
*	时间：16:39:03
*	调用者：支付回执
*	参数：请求json
*	好了吗？
*
*/
@Controller
@RequestMapping("/api")
public class ApiController  extends BaseDispatchAction{
	private static final Logger log = Logger.getLogger(ApiController.class);
	private IExpressService expressServer = (IExpressService) RemoteCall.getRemoteObject(IExpressService.class);
	
	/*
	 * 进入我的快递
	 */
	@RequestMapping(value = { "/pay.do" })
	@ResponseBody
	public String pay(HttpServletRequest request, HttpServletResponse response) 
	{
		Map<String, String> map = new HashMap<String, String>();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		log.info("["+df.format(new Date())+"] 收到订单推送信息");
		try {
			byte[] filebt = readStream(request.getInputStream());
			String dataSrc = new String(filebt,"UTF-8");
			String data = AesUtil.AESDecrypt(dataSrc);//解密
			log.info("解密前的数据："+dataSrc);
			log.info("解密后的数据："+data);
			JSONObject json = JSONObject.parseObject(data);
			String logNo = json.getString("logNo");
			String msgCd = json.getString("msgCd");
			String txnSts = json.getString("txnSts");
			BigDecimal amount = json.getBigDecimal("t4TxnAmt");
			BigDecimal feeAmount = json.getBigDecimal("mercFeeAmt");
			if("S".equals(txnSts) ||  "F".equals(txnSts))
			{
				PospPayOrderInfo payInfo = new PospPayOrderInfo();
				payInfo.setData(data);
				payInfo.setLogNo(logNo);
				payInfo.setMsgCd(msgCd);
				payInfo.setTxnSts(txnSts);
				payInfo.setAmount(amount.divide(new BigDecimal("100")));
				payInfo.setFeeAmount(feeAmount.divide(new BigDecimal("100")));
				
				Result ret = expressServer.expressInfoPay(payInfo);
				
				map.put("code", ret.getCode());
				map.put("msg" , ret.getMsg());
			}else//非最终状态不处理
			{
				map.put("code", "01");
				map.put("msg" , "非最终状态");
			}
		} catch (Exception e) {
			map.put("code", "01");
			map.put("msg" , "fail");
			log.error("["+df.format(new Date())+"] 处理订单信息失败："+e.getMessage());
			e.printStackTrace();
		}
		log.info("["+df.format(new Date())+"] 处理订单信息完成,返回数据："+net.sf.json.JSONObject.fromObject(map).toString());
		String json = JSON.toJSONString(map);
		try {
			json = AesUtil.AESEncrypt(json);
		} catch (Exception e) {
			log.info("["+df.format(new Date())+"] 返回支付回调信息加密错误");
		}
		log.info("["+df.format(new Date())+"] 加密数据："+json);
		return json;
	}
	
	

	/*
	 * 进入我的快递
	 */
	@RequestMapping(value = { "/testFuqianla.do" })
	@ResponseBody
	public String testFuqianla(HttpServletRequest request, HttpServletResponse response) 
	{
		Map map = request.getParameterMap();
		net.sf.json.JSONArray json = net.sf.json.JSONArray.fromObject(map.get("msg"));
		System.out.println(json);
		return "success";
	}
	
	@RequestMapping(value = { "/getAdrInfo.do" })
	@ResponseBody
	private Map findAddr(String lat,String lng) {
		 Map map = null;
        try{
	        String getLocal = "http://api.map.baidu.com/geocoder/v2/?ak=kZW5cygSrkcCNVCPbOwNXGGR&location="+lat+","+lng+"&output=json&pois=1&coordtype=wgs84ll";
	        org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
	        GetMethod poster = new GetMethod(getLocal);
	        httpClient.executeMethod(poster);
	        String result = poster.getResponseBodyAsString();
	        map = StrUtil.parse(result);
        }catch(Throwable e){
        	e.printStackTrace();
        	map = new HashMap();
        }
        map.put("lat", lat);
        map.put("lng", lng);//原始坐标放进去
        return map;
	}
	
	@RequestMapping(value = { "/trans.do" })
	@ResponseBody
	private Object trans(String lat,String lng) {
        try{
	       String url = "http://api.map.baidu.com/geoconv/v1/?from=1&to=5&ak=2q9aXau4p4lTSfGWZNZmIv9D";
	       url += "&coords="+lng+","+lat;
	       net.sf.json.JSONObject json = CommonUtil.httpRequest(url, CommonUtil.REQ_GET, null);
	       return json;
        }catch(Throwable e){
        	e.printStackTrace();
        	return "";
        }
	}
	
	public byte[] readStream(InputStream inStream) throws Exception {  
	    ByteArrayOutputStream outSteam = new ByteArrayOutputStream();  
	    byte[] buffer = new byte[1024];  
	    int len = -1;  
	    while ((len = inStream.read(buffer)) != -1) {  
	        outSteam.write(buffer, 0, len);  
	    }  
	    outSteam.close();  
	    inStream.close();  
	    return outSteam.toByteArray();  
	}  
}
